#!/bin/bash
# FRP 一键部署脚本

echo "🚀 开始部署 FRP..."

# 检查是否为root用户
if [ "$EUID" -ne 0 ]; then
    echo "❌ 请使用 root 用户运行此脚本"
    exit 1
fi

# 下载 FRP
FRP_VERSION="0.52.3"
FRP_FILE="frp_${FRP_VERSION}_linux_amd64.tar.gz"

echo "📥 下载 FRP ${FRP_VERSION}..."
if [ ! -f "$FRP_FILE" ]; then
    wget "https://github.com/fatedier/frp/releases/download/v${FRP_VERSION}/${FRP_FILE}"
    if [ $? -ne 0 ]; then
        echo "❌ 下载失败，尝试使用国内镜像..."
        wget "https://ghproxy.com/https://github.com/fatedier/frp/releases/download/v${FRP_VERSION}/${FRP_FILE}"
    fi
fi

# 解压
echo "📦 解压 FRP..."
tar -xzf "$FRP_FILE"
cd "frp_${FRP_VERSION}_linux_amd64"

# 复制配置文件
echo "📝 复制配置文件..."
cp ../frps.ini ./

# 设置执行权限
chmod +x frps

# 创建systemd服务
echo "🔧 创建系统服务..."
cat > /etc/systemd/system/frps.service << EOF
[Unit]
Description=Frp Server Service
After=network.target

[Service]
Type=simple
User=root
Restart=on-failure
RestartSec=5s
ExecStart=$(pwd)/frps -c $(pwd)/frps.ini
ExecReload=/bin/kill -s HUP \$MAINPID
KillMode=mixed
TimeoutStopSec=5s

[Install]
WantedBy=multi-user.target
EOF

# 开放防火墙端口
echo "🔥 配置防火墙..."
firewall-cmd --permanent --add-port=7000/tcp
firewall-cmd --permanent --add-port=8080/tcp
firewall-cmd --permanent --add-port=8443/tcp
firewall-cmd --permanent --add-port=7500/tcp
firewall-cmd --reload

# 启动服务
echo "🚀 启动 FRP 服务..."
systemctl daemon-reload
systemctl enable frps
systemctl start frps

# 检查状态
echo "📊 检查服务状态..."
systemctl status frps --no-pager

echo "✅ FRP 服务端部署完成！"
echo "📊 管理面板: http://39.102.121.104:7500 (admin/admin123)"
echo "📝 日志文件: $(pwd)/frps.log"
echo "🔧 配置文件: $(pwd)/frps.ini"
